#include "../headers/loginform.h"
#include "../ui/ui_loginform.h"
#include "../headers/MysqlUtil.h"
#include <QCryptographicHash>
#include <QtSql/QSqlDatabase>
#include <QMessageBox>
LoginForm::LoginForm(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::LoginForm)
{
    ui->setupUi(this);
    this->setFixedSize(400, 300);
    this->setWindowTitle(tr("loginForm"));
    ui->loginButton->setText(tr("loginBtn"));
    ui->resetButton->setText(tr("resetBtn"));
    ui->userNameLabel->setText(tr("userNameLab"));
    ui->passwordLabel->setText(tr("passwordLab"));
    ui->userNameLineEdit->setText("admin");
    ui->passowdLineEdit->setText("123456");
}

LoginForm::~LoginForm()
{
    delete ui;
}

void LoginForm::on_resetButton_clicked()
{
    ui->userNameLineEdit->setText("");
    ui->passowdLineEdit->setText("");
}


void LoginForm::on_loginButton_clicked()
{
    QString input_userName = ui->userNameLineEdit->text();
    QString input_password = ui->passowdLineEdit->text();
    //QString input_password = QCryptographicHash::hash(ui->passowdLineEdit->text().toLatin1(), QCryptographicHash::Md5).toHex();

    QSqlDatabase db;
    connect_to_database(db);
    QSqlQuery query(db);

    if(input_userName.isEmpty() || input_password.isEmpty())
    {
        // QMessageBox::warning(this, "登录失败", "请输入用户密码！");
        QMessageBox::warning(this, tr("login_error"), tr("login_param_error"));
    }else{
        query.exec("select adminName from admin where adminName = '" + input_userName + "'");
        if(!query.next())
        {
            // QMessageBox::warning(this, "登录失败", "该用户不存在！");
            QMessageBox::warning(this,tr("login_error"), tr("login_user_not_exit_error"));
            return;
        }
        query.exec("select id, adminName, password from admin where adminName = '" + input_userName + "' and password = '" + input_password + "'");
        bool isLoginSuccess = false;
        if(query.next())
        {
            QString id = query.value(0).toString();
            QString userName = query.value(1).toString();
            QString pwd = query.value(2).toString();
            Admin loginAdmin;
            loginAdmin.setAdminName(userName);
            loginAdmin.setPassword(pwd);
            loginAdmin.setId(id);
            isLoginSuccess = true;
            this->hide();
            m.show();
        }
        if(!isLoginSuccess)
        {
            // QMessageBox::warning(this, "登录失败", "密码错误！");
            QMessageBox::warning(this, tr("login_error"),tr("login_password_error"));
            ui->passowdLineEdit->setFocus();
        }
    }
}

